from fastapi import APIRouter, HTTPException,Request
from fastapi.responses import JSONResponse
from utils.response import standard_response
from utils.log_utils import logger
from utils.email import send_email
from db.database import engine
from schemas import  SensitiveReport
import smtplib
from email.message import EmailMessage
from fastapi import APIRouter, Body, Depends, Query, Path
from sqlalchemy.orm import Session
from typing import List, Optional
import logging

from db.database import get_db
from schemas.info_schema import (
    InfoPublishCreate, InfoPublishUpdate, InfoPublishQuery,
    InfoPublishInfo,InfoPublishSave
)
from curd.info_curd import InfoPublishCRUD
from models.index import ResponseModel, ResponseList
# 创建一个 APIRouter 实例

router = APIRouter(prefix="/test", tags=["测试接口"])


@router.get("/pool-status")
def pool_status():
    return {
        "checked_out": engine.pool.checkedout(),
        "checked_in": engine.pool.checkedin(),
        "connections": engine.pool.status()
    }

@router.post("/send-email")
async def report_sensitive(report: SensitiveReport):
    # 参数校验
    if not all([report.type, report.userId]):
        raise HTTPException(400, "缺少必要参数")
    
    # 构建告警信息
    alert_content = f"""
    报警类型：{report.type}
    关联ID：{report.id}
    用户ID：{report.userId}
    店铺ID：{report.shopid}
    店铺编码：{report.shopCode}
    租户ID：{report.tenantid}
    租户编码：{report.tenantCode}
    敏感词详情：{report.sensitiveDetails}
    """
    
    try:
        await send_email(alert_content)
        return {"status": "success", "message": "警告已发送"}
    except Exception as e:
        raise HTTPException(500, f"邮件发送失败: {str(e)}")

@router.get("/cors-test")
async def cors_test():
    """
    CORS测试接口
    用于验证跨域请求是否正常工作
    """
    return standard_response(
        code=200,
        message="CORS配置成功！跨域请求正常工作",
        data={
            "timestamp": "2024-01-01T00:00:00Z",
            "status": "success",
            "cors_enabled": True
        }
    )

@router.post("/cors-post-test")
async def cors_post_test(data: dict):
    """
    CORS POST请求测试接口
    """
    return standard_response(
        code=200,
        message="CORS POST请求测试成功",
        data={
            "received_data": data,
            "timestamp": "2024-01-01T00:00:00Z",
            "method": "POST"
        }
    )

@router.options("/cors-options-test")
async def cors_options_test():
    """
    CORS OPTIONS请求测试接口
    用于预检请求测试
    """
    return JSONResponse(
        content={"message": "OPTIONS请求处理成功"},
        headers={
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
            "Access-Control-Allow-Headers": "Content-Type, Authorization"
        }
    )




@router.get('/info/{info_id}', summary="获取信息详情")
def get_info_detail(
    info_id: str = Path(..., description="信息ID"),
    db: Session = Depends(get_db)
):
    """根据ID获取信息详情"""
    try:
        # 调用CRUD层获取信息
        db_info = InfoPublishCRUD.get_info_by_id(db, info_id)
        
        if not db_info:
            return ResponseModel.error(code=404, message="信息不存在")
        
        return ResponseModel.success(data=db_info, message="获取信息成功")
    except Exception as e:
        logger.error(f"获取信息失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"获取信息失败: {str(e)}")


@router.post('/infos', summary="获取信息列表")
def get_info_list(
    query_params: InfoPublishQuery = Body(..., description="查询参数"),
    db: Session = Depends(get_db)
):
    """获取信息列表（支持分页和筛选）"""
    try:
        # 调用CRUD层查询信息
        result = InfoPublishCRUD.get_infos(db, query_params)
        
        # 构建符合ResponseList.success要求的参数格式
        response_data = {
            'data': result['items'],
            'total': result['total'],
            'pageIndex': query_params.pageIndex,
            'pageSize': query_params.pageSize
        }
        return ResponseList.success(data=response_data, message="获取信息列表成功")
    except Exception as e:
        logger.error(f"获取信息列表失败: {str(e)}")
        return ResponseList.error(code=500, message=f"获取信息列表失败: {str(e)}")




@router.delete('/info/{info_id}', summary="删除信息")
def delete_info(
    info_id: str = Path(..., description="信息ID"),
    db: Session = Depends(get_db)
):
    """删除信息（软删除，将状态改为失效）"""
    try:
        # 调用CRUD层删除信息
        success = InfoPublishCRUD.delete_info(db, info_id)
        
        if not success:
            return ResponseModel.error(code=404, message="信息不存在")
        
        logger.info(f"删除信息成功: id={info_id}")
        return ResponseModel.success(message="删除信息成功")
    except Exception as e:
        logger.error(f"删除信息失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"删除信息失败: {str(e)}")


# 新增统一保存接口
@router.post('/save-info', summary="保存信息（创建/更新）")
async def save_info(
    request: Request,  # 新增Request参数
    info_data: InfoPublishSave = Body(...),
    db: Session = Depends(get_db)
):
    user_id = request.state.userId  # 从请求上下文中获取用户ID
    
    if info_data.id:
        # 更新操作
        info_data.update_by = user_id
    else:
        # 创建操作
        info_data.create_by = user_id
    
    msg = ""  # 初始化msg变量

    try:
        if info_data.id:
            # 更新逻辑 - 修改这里，使用InfoPublishUpdate模型来传递所有可更新字段
            update_data = InfoPublishUpdate(
                content=info_data.content,
                info_type=info_data.info_type,
                type_id=info_data.type_id,
                status=info_data.status,
                update_by=info_data.update_by
            )
            db_info = InfoPublishCRUD.update_info(db, info_data.id, update_data)
            msg = "更新"
        else:
            # 创建逻辑
            db_info = InfoPublishCRUD.create_info(db, info_data)
            msg = "创建"
            
        if not db_info:
            return ResponseModel.error(code=500, message=f"{msg}信息失败")
            
        logger.info(f"{msg}信息成功: id={getattr(db_info, 'id', '')}")
        return ResponseModel.success(data=db_info, message=f"{msg}信息成功")
    except Exception as e:
        # 确保msg有默认值，避免UnboundLocalError
        operation = msg if msg else "保存"
        logger.error(f"{operation}信息失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"{operation}信息失败: {str(e)}")

# 需要同步修改的Schema模型（在info_schema.py中添加）：